//
//  WebLinkListCell.swift
//  Wallpaper
//
//  Created by YEHWANG-iOS on 2024/10/29.
//

import UIKit

class WebLinkListCell: UICollectionViewCell {

    @IBOutlet weak var downBtn: UIButton!
    @IBOutlet weak var state: UIActivityIndicatorView!
    
    var imageView: LKImageView!
    
    override func awakeFromNib() {
        super.awakeFromNib()
    
        if #available(iOS 13.0, *) {
            downBtn.isHidden = true
        } else {
            downBtn.isHidden = false
        }
        
        imageView = LKImageView(frame: bounds)
        imageView.delegate = self
        imageView.delayLoadingImage = false
        contentView.insertSubview(imageView, at: 0)
        imageView.imageManager = ImageURLRequestTool.imageWallManager
        imageView.backgroundColor = UIColor.hex(hexString: "#f2f2f2")
        imageView.clipsToBounds = true
        self.clipsToBounds = true
        imageView.scaleMode = .aspectFill
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        imageView.frame = self.bounds
    }
    
    override func prepareForReuse() {
        state.stopAnimating()
        imageView.image = nil
    }

}

extension WebLinkListCell: LKImageViewDelegate {
    func lkImageViewImageLoading(_ imageView: LKImageView, request: LKImageRequest) {
        //进度request.progress
        if request.isFinished || request.isCanceled {
            state.stopAnimating()
        } else {
            state.startAnimating()
        }

    }
    
    func lkImageViewImageDidLoad(_ imageView: LKImageView, request: LKImageRequest) {
        state.stopAnimating()
    }
}

class ImageURLRequestTool: NSObject {
    
    class var imageWallManager: LKImageManager {
        return ImageURLRequestTool.shared.manager
    }

    static let shared = ImageURLRequestTool()
    
    private var manager: LKImageManager!
    
    override init() {
        super.init()
        
        let config = LKImageConfiguration.default()
        manager = LKImageManager(configuration: config)
        
        LKImageLogManager.instance().registerListener { _, _ in
            
        }
    }
}
